package cn.leedsoft.and.crimeintent.model.photo_gallery;

import android.net.Uri;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.annotation.Nullable;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * Created by leeds on 2016/8/24 9:52.
 */
public class PhotoHttpFetcher {
    private static final CloseableHttpClient httpClient = HttpClients.createDefault();
    private static final String ENDPOINT = "http://apis.baidu.com/txapi/mvtp/meinv";
    private static final String PARAM_NUM = "num";
    private static final String API_KEY = "apikey";
    private static final String API_KEY_VALUE = "c465e3db93b1870b1db5df5ffa2c287c";

    public List<GalleryItem> fetch(int num) {
        if(num < 0) num = 0;
        String url = Uri.parse(ENDPOINT)
                .buildUpon().appendQueryParameter(PARAM_NUM, String.valueOf(num)).build().toString();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader(API_KEY, API_KEY_VALUE);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return parse2GalleryItem(EntityUtils.toString(entity));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Lists.newArrayList();
    }
    public List<GalleryItem> fetch() {
        return fetch(30);
    }

    private List<GalleryItem> parse2GalleryItem(String jsonString) {
        JSONObject resJson = JSON.parseObject(jsonString);
        if (resJson.getIntValue("code") == 200) {
            JSONArray newslist = resJson.getJSONArray("newslist");
            return Lists.transform(newslist, new Function<Object, GalleryItem>() {
                @Override
                public GalleryItem apply(@Nullable Object input) {
                    JSONObject jsonObject = (JSONObject) input;
                    GalleryItem item = new GalleryItem();
                    item.setUri(jsonObject.getString("picUrl"));
                    item.setTitle(jsonObject.getString("title"));
                    item.setDescription(jsonObject.getString("description"));
                    item.setPageUrl(jsonObject.getString("url"));
                    try {
                        item.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(jsonObject.getString("ctime")));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    return item;
                }
            });
        } else return Lists.newArrayList();
    }

    public byte[] fetchBytes(String url) {
        HttpGet httpGet = new HttpGet(url);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toByteArray(entity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
